const express = require("express");
const router = express.Router();
const { getBigProducts, searchProducts } = require("./../models/product");

const BASE_URL = process.env.API_HOST + ":" + process.env.API_PORT;
console.log(BASE_URL);
// 购物车路由
router.get("/get/products", async (req, res) => {
  try {
    const { limit, offset } = req.query;
    console.log("Search endpoint called",limit, offset);
    const { products, totalPages } = await getBigProducts(limit, offset);
    products.forEach((element) => {
      element.image = BASE_URL + element.image;
    });
    return res.status(200).json({
      code: 0,
      success: true,
      data: products,
      pagination: { totalPages },
    });
  } catch (error) {
    console.error("Search endpoint error:", error);
    res.status(500).json({
      success: false,
      message: "Server error",
      error: error.message,
    });
  }
});
// 搜索商品接口
router.get("/products/search", async (req, res) => {
  console.log("Search endpoint called");
  try {
    const { keyword } = req.query;
    console.log("搜索关键词", keyword);
    if (!keyword) {
      return res
        .status(400)
        .json({ success: false, message: "搜索关键词不能为空" });
    }
    let products = await searchProducts(keyword);
    products.forEach((element) => {
      element.image = BASE_URL + element.image;
    });
    return res.status(200).json({
      code: 0,
      success: true,
      data: products,
      pagination: {},
    });
  } catch (error) {
    console.error("Search endpoint error:", error);
    res.status(500).json({
      success: false,
      message: "Server error",
      error: error.message,
    });
  }
});

module.exports = router;
